package com.springboot.frame.starter.web.cors;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * Cors 的spring-boot启动器
 *
 * @author liheng
 */
@Configuration
@EnableConfigurationProperties(CorsProperties.class)
@ConditionalOnProperty(name = "web.cors.enabled")
@ConditionalOnClass(UrlBasedCorsConfigurationSource.class)
public class CorsAutoConfiguration {

    /**
     * cors配置参数
     */
    private final CorsProperties properties;

    public CorsAutoConfiguration(CorsProperties properties) {
        this.properties = properties;
    }

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许任何域名使用
        corsConfiguration.addAllowedOriginPattern(properties.getAllowedOrigins());
        corsConfiguration.addAllowedOrigin("null");
        // allowCredential 需设置为true
        corsConfiguration.setAllowCredentials(true);
        // 允许任何头
        corsConfiguration.addAllowedHeader(properties.getAllowedHeaders());
        // 允许任何方法（post、get等）
        corsConfiguration.addAllowedMethod(properties.getAllowedMethods());
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 对接口配置跨域设置
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}
